#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024-08-15 20:03:49
# @File           : views.py
# @IDE            : PyCharm
# @desc           : 帮助中心视图

from typing import List
from fastapi import APIRouter, Depends, Request, UploadFile
from fastapi.params import Body
from sqlalchemy import not_
from sqlalchemy.orm import joinedload
from core.exception import CustomException
from utils.response import SuccessResponse
from . import schemas, crud, params, models
from .utils.grouping import TaskPoolGrouper
from apps.base.auth.validate import Auth, AllUserAuth
from core.dependencies import IdList


app = APIRouter()


###################################################
#   任务池管理                                      #
###################################################
@app.post("/task/pool", summary="新增生产任务信息")
async def create_task(
        data: schemas.TaskIn,
        auth: Auth = Depends(AllUserAuth())
):
    data.create_user = auth.user.user_str
    return SuccessResponse(await crud.TaskPoolDal(auth.db).create_data(data))


@app.get("/task/pool", summary="获取生产任务池列表", description="包含所有信息：派工结果、反馈的问题")
async def get_tasks(
        p: params.TaskParams = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    datas, count = await crud.TaskPoolDal(auth.db).get_tasks(
        **p.dict(),
        v_return_count=True,
    )
    return SuccessResponse(datas, count=count)


@app.get("/task/pool/{ticket_id}", summary="获取生产任务详情", description="包含所有信息：派工结果、反馈的问题")
async def get_task_detail(
        ticket_id: str,
        auth: Auth = Depends(AllUserAuth())
):
    data = await crud.TaskPoolDal(auth.db).get_data(
        ticket_id=ticket_id,
        v_options=[
            joinedload(models.DCTask.feedback),
            joinedload(models.DCTask.assign_users),
            joinedload(models.DCTask.work_teams),
            joinedload(models.DCTask.needs),
        ],
        v_schema=schemas.TaskOut,
    )
    return SuccessResponse(data)


@app.put("/task/pool/{data_id}", summary="更新生产任务信息", description="可更新排序, 分组字段")
async def update_task(
        data_id: int,
        data: schemas.TaskUpdate,
        auth: Auth = Depends(AllUserAuth())
):
    data.update_user = auth.user.user_str
    return SuccessResponse(await crud.TaskPoolDal(auth.db).put_data(data_id, data))


@app.delete("/task/pool", summary="批量删除生产任务", description="软删除")
async def delete_task(
        ids: IdList = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    await crud.TaskPoolDal(auth.db).delete_datas(ids=ids.ids, v_soft=False)
    return SuccessResponse("删除成功")


@app.get("/task/tree", summary="获取生产任务分组树", description="分架次、工位、二次工位、班组、自定义分组")
async def get_tasks_tree(
        p: params.TaskGroupParams = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    datas = await crud.TaskPoolDal(auth.db).get_datas(
        **p.dict(),
        limit=0,
        v_return_objs=True,
    )
    grouper = TaskPoolGrouper(datas)
    grouper.group_tasks()
    return SuccessResponse(grouper.group_list)


@app.get("/task/sync", summary="从工单同步生产任务", description="手动触发工单同步和更新")
async def async_tasks(
        request: Request,
        p: params.TaskGroupParams = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    data = await crud.TaskPoolDal(auth.db).fetch_tasks(request, **p.dict())
    return SuccessResponse(data)


@app.get("/task/options", summary="工单状态选择项")
async def get_tasks_options(
        auth: Auth = Depends(AllUserAuth())
):
    data = await crud.TaskPoolDal(auth.db).get_status_options()
    return SuccessResponse(data)


@app.get("/task/query", summary="远程查询工单号", description="远程查询工单号")
async def query_tasks(
        p: params.TaskQueryParams = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    datas = await crud.TaskPoolDal(auth.db).get_datas(
        **p.dict(),
        v_schema=schemas.TaskQueryOut
    )
    return SuccessResponse(datas)


###################################################
#   文件上传下载                                   #
###################################################
@app.get("/task/template", summary="下载任务依赖导入模板")
async def get_task_template(
    auth: Auth = Depends(AllUserAuth())
):
    return SuccessResponse(await crud.TaskPoolDal(auth.db).download_import_template())


@app.get("/task/files", summary="获取已上传的依赖数据")
async def get_task_template_files(
    auth: Auth = Depends(AllUserAuth())
):
    datas, count = await crud.TaskPoolDal(auth.db).get_template_data()
    return SuccessResponse(datas, count=count)


@app.post("/task/export", summary="导出任务列表")
async def export_task_list(
    header: List = Body(..., title="表头对应字段"),
    p: params.TaskParams = Depends(),
    auth: Auth = Depends(AllUserAuth())
):
    data = await crud.TaskPoolDal(auth.db).export_query_list(
        header,
        **p.dict(),
    )
    return SuccessResponse(data)


@app.get("/task/assignment2", summary="获取派工的任务，以任务表为主表")
async def get_task_assignment2(
        p: params.TaskParams = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    v_where = []
    if p.is_not_assign:
        v_where.append(not_(models.DCTask.assign_users.any()))      

    del p.is_not_assign
    
    datas, count = await crud.TaskPoolDal(auth.db).get_datas(
        **p.dict(),
        v_where=v_where,
        v_options=[
            joinedload(models.DCTask.assign_users),
        ],
        v_schema=schemas.TaskOutWithAssignments,
        v_return_count=True,
    )
    return SuccessResponse(datas, count=count)


@app.get("/task/feedback2", summary="获取反馈问题的任务，以任务表为主表")
async def get_task_feedback2(
        p: params.TaskParams = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    v_where = []
    if p.is_not_assign:
        v_where.append(not_(models.DCTask.assign_users.any()))      

    del p.is_not_assign
    
    datas, count = await crud.TaskPoolDal(auth.db).get_datas(
        **p.dict(),
        v_where=v_where,
        v_options=[
            joinedload(models.DCTask.feedback),
        ],
        v_schema=schemas.TaskOutWithFeebacks,
        v_return_count=True,
    )
    return SuccessResponse(datas, count=count)